package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiduMapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.BaiduMapUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.jdom2.input.sax.SAXEngine;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private BaiduMapUtil baiduMapUtil;
    @Autowired
    private BaiduMapProperties properties;
    //地理编码接口，获取地址的经纬度坐标
    private static final String LOCATION_URL = "https://api.map.baidu.com/geocoding/v3";

    /**
     * 用户下单--最终目的，将订单数据存入表中
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional//多个表有修改，开启事务
    public OrderSubmitVO addOrder(OrdersSubmitDTO dto) {
        //查询地址表查询收货人
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户表，获取用户相关信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //调用工具类校验配送范围
        //获取店铺坐标
        String origin = baiduMapUtil.getShopLocation(LOCATION_URL);
        //构造工具类所需要数据。用于获取目的地坐标
        Map<String, String> paramMap = new HashMap<>();
        //构造目的地地址参数
        String address = addressBook.getProvinceName() +
                addressBook.getCityName() +
                addressBook.getDistrictName() +
                addressBook.getDetail();

        paramMap.put("address", address);
        paramMap.put("ak", properties.getAK());
        paramMap.put("output", "json");
//        paramMap.put("callback", "showLocation");
        //获取目的地坐标
        String destination = baiduMapUtil.getLocation(LOCATION_URL, paramMap);
        //调用工具类校验配送范围
        if (!baiduMapUtil.checkDistributionScope(origin, destination, properties.getRideUrl())) {
            throw new OrderBusinessException(MessageConstant.OUT_OF_RANGE);
        }

        // 1.构造订单数据
        Orders orders = new Orders();
        // 2.插入订单数据到orders表中
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());//查询地址表查询收货人手机号
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());//收货人//查询地址表查询收货人
        orders.setUserName(user.getName());//根据当前登录用户id查询当前下单的人名
        ordersMapper.insert(orders);
        // 3.构造订单明细列表数据--从购物车获取订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();//查询购物车放入集合
        //循环遍历购物车明细数据，存入oreder_detail中
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        //批量插入订单明细数据        // 4.将订单明细列表数据批量插入到order_detail表中
        orderDetailMapper.insertBatch(orderDetails);
        // 5.清空购物车数据（自己名下的）
        shoppingCartMapper.delete(ShoppingCart.builder().id(userId).build());
        // 6.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
/*        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);*/
/*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        //模拟支付成功
        //由于小程序id和商户id不匹配（或者没有商户id），所以无法返回预支付标识，为看到支付成功效果，注释掉上面判断逻辑，直接模拟下面页面跳转
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        //业务逻辑是清空购物车，并往购物车内添加订单里的商品数据
        //前端会自动调用清空购物车接口，只要写后面逻辑就行
        //先通过订单id查出订单详情里的商品数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //创建list集合，遍历把商品数据放进去，然后插入购物车表里
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        Long userId = BaseContext.getCurrentId();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            log.info("购物车商品：{}", shoppingCart);
            //补充userId和创建时间
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }

        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> orderVOPage = ordersMapper.conditionSearch(dto);
        List<OrderVO> orderVOList = orderVOPage.getResult();
        //获取订单id
        List<Long> orderIds = orderVOList.stream().map(Orders::getId).collect(Collectors.toList());

        int index = 0;
        for (Long orderId : orderIds) {
            StringBuilder orderDetailes = new StringBuilder();
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
            //拼接
            for (OrderDetail orderDetail : orderDetails) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                orderDetailes.append(name).append("*").append(number).append("; ");
            }
            //给订单的菜品赋值
            orderVOList.get(index++).setOrderDishes(orderDetailes.toString());
        }
        return new PageResult(orderVOPage.getTotal(), orderVOList);
    }

    //接单
    @Override
    public void newlyIncreased(Orders orders1) {
        Orders orders = ordersMapper.getById(orders1.getId());
        //判断订单状态
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            //订单状态为派送中，修改订单状态为已完成
            Orders order = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.CONFIRMED)
                    .build();
            ordersMapper.update(order);
        }
    }

    //拒单
    @Override
    public void shareTheBill(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = ordersMapper.getById(ordersRejectionDTO.getId());
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            //订单状态为待接单，修改订单状态为已取消
            Orders order = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.CANCELLED)
                    .payStatus(Orders.REFUND)
                    .cancelTime(LocalDateTime.now())
                    .build();
            ordersMapper.update(order);
        }
    }


    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer countConfirmed = ordersMapper.countConfirmed();
        Integer countDeliveryInProgress = ordersMapper.countDeliveryInProgress();
        Integer countToBeConfirmed = ordersMapper.countToBeConfirmed();
        return OrderStatisticsVO.builder()
                .confirmed(countConfirmed)
                .deliveryInProgress(countDeliveryInProgress)
                .toBeConfirmed(countToBeConfirmed)
                .build();
    }

    /**
     * 查询历史订单
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        Long userId = BaseContext.getCurrentId();
        dto.setUserId(userId);
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> orders = ordersMapper.page(dto);
        orders.forEach(orderVO -> {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        });
        return new PageResult(orders.getTotal(), orders.getResult());
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        OrderVO vo = new OrderVO();
        //获得订单基础信息
        Orders orders = ordersMapper.getById(id);
        //获得订单信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        //封装VO
        BeanUtils.copyProperties(orders, vo);
        vo.setOrderDetailList(orderDetailList);
        return vo;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(6);
        ordersMapper.updateStatus(orders);
    }

    /**
     * 商家-取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrders(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 订单派送
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 订单完成
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }
}
